import turtle
import random
# 生成随机验证码文本
def generate_captcha(length=4):
    captcha = ''
    for _ in range(length):
        # 随机选择生成大写字母(65-90)还是小写字母(97-122)
        ascii_code = random.choice([random.randint(65, 90), random.randint(97, 122)])
        # 将ASCII码转换为对应的字符，并加到验证码字符串中
        captcha += chr(ascii_code)
    return captcha
# 在画布上绘制随机斜线
def draw_random_line():
    """在画布上绘制随机斜线"""
    turtle.penup()
    turtle.goto(random.randint(-100, 100), random.randint(-50, 50))
    turtle.pendown()
    turtle.goto(random.randint(-100, 100), random.randint(-50, 50))
    turtle.penup()
# 在画布上绘制验证码文本
def draw_captcha_text(text):
    turtle.penup()
    # 根据文本长度计算起始绘制位置
    start_x = -len(text) * 15
    turtle.goto(start_x, -15)
    turtle.pendown()
    for character in text:
        # 绘制每个字符，并向右移动30个像素绘制下一个字符
        turtle.write(character, move=True, align="left", font=("Arial", 24, "normal"))
        turtle.penup()
        turtle.forward(30)
        turtle.pendown()
    turtle.penup()
def main():
    turtle.speed(0)  # 设置turtle的速度，0是最快的
    turtle.hideturtle()  # 隐藏turtle图标
    turtle.bgcolor("white")  # 设置背景颜色
    # 生成随机验证码文本
    captcha_text = generate_captcha(4)
    # 绘制斜线作为背景
    turtle.color('black')
    for _ in range(20):
        draw_random_line()
    # 绘制验证码文本
    draw_captcha_text(captcha_text)
    # 显示绘制结果，并等待用户关闭窗口
    turtle.done()
main()
